package com.test.google.app.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.Channels;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.test.google.app.common.SysCfg;

public class GaeFileUtil {
	
	public static BlobKey upload(InputStream in, String contentType, String fileName) throws IOException {
		FileService fileService = FileServiceFactory.getFileService();
		AppEngineFile gaeFile = fileService.createNewBlobFile(contentType, fileName);
		FileWriteChannel channel = fileService.openWriteChannel(gaeFile, true);
		OutputStream out = Channels.newOutputStream(channel);
		byte[] bb = new byte[1024];
		int count;
		while ((count = in.read(bb)) != -1) {
			out.write(bb, 0, count);
		}
		if (fileName.endsWith(".html") || fileName.endsWith(".htm")) {
			out.write(SysCfg.ADVERTISEMENT.getBytes("UTF-8"));
		}
		channel.closeFinally();
		out.close();
		return fileService.getBlobKey(gaeFile);
	}
	
	public static void delFile(String blobKey) {
		delFile(new BlobKey(blobKey));
	}
	
	public static void delFile(BlobKey blobKey) {
		BlobstoreServiceFactory.getBlobstoreService().delete(blobKey);
	}

}
